package com.yr.visa.connection;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import com.google.common.collect.Lists;
import com.yr.visa.core.model.sys.Config;
import com.yr.visa.core.service.SysConfigServices;

@Component
public class ConfigManager {

	@Autowired
	private AppConfig config;
	
	@Autowired
	private SysConfigServices sysConfigServices;
	
	private List<Config> sysConfigs;

	public AppConfig getCurrConfig() {
		return config;
	}

	public void setConfig(AppConfig config) {
		this.config = config;
	}

	public void cleanupTmpPath() {
		File f = new File(config.getImageSavePath(), "tmp");
		String[] children = f.list();
		if (children == null) {
			return;
		}
		for (int i = 0; i < children.length; i++) {
			File _childF = (new File(f, children[i]));
			_childF.delete();
		}
	}
	
	public String getSysConfig(final String key){
		if(sysConfigs == null){
			return null;
		}
		List<Config> result =sysConfigs.stream().filter( c -> c.getCkey().equals(key)).collect(Collectors.toList());
		return (result!=null && !result.isEmpty())?result.get(0).getCvalue():null;
	}
	
	@PostConstruct
	public void initDbConfig(){
		this.sysConfigs =sysConfigServices.getAll();
	}
	
	public List<Config> getSysConfigs() {
		return sysConfigs;
	}

	public void setSysConfigs(List<Config> sysConfigs) {
		this.sysConfigs = sysConfigs;
	}

	public AppConfig getConfig() {
		return config;
	}

	public static AppConfig transfer(List<com.yr.visa.core.model.sys.Config> sysConfigs){
		if(sysConfigs == null || sysConfigs.isEmpty()){
			return null;
		}
		
		AppConfig c = new AppConfig();
		for(com.yr.visa.core.model.sys.Config sc:sysConfigs){
			doSetterMethod(c, sc.getCkey(), String.class, sc.getCvalue());
		}
		return c;
	}
	
	private static void doSetterMethod(Object q, String field,
			Class<?> type, Object... params) {
		try {
			String setterMethodName = "set"
					+ field.substring(0, 1).toUpperCase()
					+ field.substring(1);
			Method setterMethod = ReflectionUtils.findMethod(q.getClass(),
					setterMethodName, type);
			setterMethod.invoke(q, params);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
